package com.github.common.extend.demo.config.validator;

import com.github.common.extend.demo.config.VerifyEnum;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;
import java.util.Collection;
import java.util.Objects;

/**
 * @author wangjj7
 * @date 2024/4/22
 * @description
 */
public class EnumOfListValidator implements ConstraintValidator<EnumOfList, Object> {

    private Class<? extends VerifyEnum> enumClass;

    private boolean allowEmpty;

    @Override
    public void initialize(EnumOfList constraintAnnotation) {
        this.enumClass = constraintAnnotation.enums();
        this.allowEmpty = constraintAnnotation.allowEmpty();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (value == null){
            return allowEmpty;
        }
        if (value instanceof Collection){
            Collection<?> collection = (Collection<?>) value;
            if (CollectionUtils.isEmpty(collection)){
                return allowEmpty;
            }
            if (collection.stream().anyMatch(item -> !isMatch(item))){
                return false;
            }
            return true;
        }
        if (value instanceof String) {
            if (StringUtils.isBlank((String) value)){
                return allowEmpty;
            }
        }
        return isMatch(value);
    }

    private boolean isMatch(Object value) {
        return Arrays.stream(enumClass.getEnumConstants())
                .filter(VerifyEnum.class::isInstance)
                .map(VerifyEnum.class::cast)
                .anyMatch(e -> Objects.equals(e.getVerifyValue() ,value));
    }

}
